// pages/recipe/add/add.js
Page({
  data: {
    db:null,
    image:'',
    nickName:'',
    nameCode:'',
    description:'',
    _id:'',
    userInfo: {},
    isLoggedIn:false,
  },
  onLoad(options) {
    // 在任何页面/组件中获取
    const app = getApp();
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db,
      userInfo:wx.getStorageSync('userInfo'),
      image:wx.getStorageSync('userInfo').avatarUrl,
      nickName:wx.getStorageSync('userInfo').nickName,
      description:wx.getStorageSync('userInfo').description,
      nameCode:wx.getStorageSync('userInfo').nameCode,
      _id:wx.getStorageSync('userInfo')._id
    })
  },
  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log('res',res)
        const tempFilePaths = res.tempFilePaths
        // this.setData({
        //   image: tempFilePaths[0]
        // })
        // 这里可以添加图片上传到云存储的逻辑
        this.uploadImage(tempFilePaths[0])
      }
    })
  },

  // 移除图片
  removeImage() {
    this.setData({
      image: ''
    })
  },

  // 上传图片到云存储
  uploadImage(filePath) {
    wx.showLoading({
      title: '上传中...',
    })
    
    wx.cloud.uploadFile({
      cloudPath: 'recipe-images/' + Date.now() + '-' + Math.random().toString().substr(2, 5) + '.jpg',
      filePath: filePath,
      success: res => {
        console.log('上传成功', res.fileID)
        this.setData({
          image: res.fileID
        })
        wx.hideLoading()
      },
      fail: err => {
        console.error('上传失败', err)
        wx.hideLoading()
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    })
  },

  // 昵称
  onNameChange(e) {
    this.setData({
      nickName: e.detail.value
    })
  },
  // 描述变化
  onDescriptionChange(e) {
    this.setData({
      description: e.detail.value
    })
  },
  // 表单验证
  validateForm() {
    if (!this.data.nickName.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return false
    }
    return true
  },

  // 提交表单
  submitForm() {
    if (!this.validateForm()) return
    const formData = {
      avatarUrl: this.data.image,
      nickName:this.data.nickName,
      description: this.data.description
    }
    wx.showLoading({
      title: '提交中...',
    })

      formData.updateTime = new Date()
      this.data.db.collection('userList').doc(this.data._id).update({
        data: formData,
        success: res => {
          console.log('res formData',res)
          console.log('更新成功')
          this.data.db.collection('inviterList')
          .where({
            interver: this.data.nameCode // 筛选条件：nameCode 等于当前用户的 nameCode
          })
          .update({
            data: {
              interver_avatarUrl: this.data.image,
              interver_nickName:this.data.nickName,
            },
            success: res => {
              console.log('update interver',res)
            },
          })
          this.data.db.collection('message')
          .where({
            _openid:this.data.userInfo._openid
          })
          .update({
            data: {
              avatarUrl: this.data.image,
              nickName:this.data.nickName,
            },
            success: res => {
              console.log('update interver',res)
            },
          })
          this.data.db.collection('userList').where({
            _id:this.data._id
          }).get()
          .then(res => {
            if(res && res.data && res.data.length > 0){
              wx.setStorageSync('userInfo', res.data[0])
              this.back()
            }
          })
        }
      })
  },

  back(){
    wx.navigateBack()
  },
})